<?php

/**
 * 自动生成 MerWxSettingService
 * 
 * Apps/Common/Service/MerWxSettingService.class.php
 * admin @ 2015-06-16
 */

namespace Common\Service;

use Common\Service\SysDictionaryService;

class MerWxSettingService {

  private static $instance;
  var $type_text = array(
    '订阅号' => 30,
    '服务号' => 31,
    '企业号' => 32
  );

  public static function instance() {
    if (self::$instance == null) {
      $instance = new MerWxSettingService ();
    }

    return $instance;
  }

  function get_default_row() {
    return array(
      'mer_id' => '0',
      'user_name' => '',
      'password' => '',
      'name' => '',
      'app_id' => '',
      'app_secret' => '',
      'pay_setting1' => '',
      'pay_setting2' => '',
      'pay_setting3' => '',
      'mer_wx_menu' => '',
      'create_date' => date('Y-m-d H:i:s'),
      'update_date' => date('Y-m-d H:i:s'),
      'expire_date' => ''
    );
  }

  function get_status() {
    $SysDictionary = SysDictionaryService::instance();
    return $SysDictionary->get_wx_type();
  }

  function get_by_id($id) {
    $MerWxSetting = M('MerWxSetting');
    $data = $MerWxSetting->find($id);
    return $data ? $data : array();
  }
    
  function get_by_mer_id_and_type($mer_id, $type) {
    $MerWxSetting = M('MerWxSetting');
    $where = array(
      "mer_id" => $mer_id,
      "type" => $type
    );
    $data = $MerWxSetting->where($where)
      ->find();
    return $data ? $data : array();
  }

  function get_by_cond($config) {
    $default = array(
      'mer_id' => '',
      'page' => 1,
      'page_size' => 6,
      'status' => '',
      'count' => FALSE,
      'order' => 'ASC',
      'sort' => 'sort'
    );

    $config = extend($config, $default);

    $MerWxSetting = M('MerWxSetting');

    $where = array();

    if (!empty($config ['status'])) {
      $where ['status'] = $config ['status'];
    }

    if (!empty($config ['mer_id'])) {
      $where ['mer_id'] = $config ['mer_id'];
    }

    if ($config ['count']) {
      return $MerWxSetting->where($where)
          ->count();
    } else {
      $order = $config ['sort'] . ' ' . $config ['order'];
      $limit = $config ['page'] > 0 ? ($config ['page'] - 1) * $config ['page_size'] . ' , ' . $config ['page_size'] : '';
      $data = $MerWxSetting->where($where)
        ->limit($limit)
        ->order($order)
        ->select();
      // echo $MerWxSetting->_sql();
      return $data ? $data : array();
    }
  }

  function create($data) {
    $data ['password'] = trim($data ['password']);
    $data ['username'] = trim($data ['username']);

    $post = array(
      'f' => 'json',
      'imgcode' => '',
      'pwd' => md5($data ['password']),
      'username' => $data ['username']
    );

    $login_ret = $this->_login($post);
    // print_r($login_ret);
    if (!$login_ret ['status']) {
      return $login_ret;
    }

    $check_data = $this->get_by_wx_no($login_ret ['data'] ['wx_no']);
    if (!empty($check_data)) {
      return ajax_arr('该公众号号已经添加过了');
    }
    $login_ret ['data'] ['mer_id'] = $data ['mer_id'];
    $login_ret ['data'] ['user_name'] = $data ['username'];
    $login_ret ['data'] ['password'] = md5($data ['password']);

    $MerWxSetting = M('MerWxSetting');
    $ret = $MerWxSetting->add($login_ret ['data']);
    if ($ret) {
      return ajax_arr('添加成功', TRUE, array(
        'id' => $ret
        ));
    } else {
      return ajax_arr('添加失败', FALSE);
    }
  }

  function get_by_wx_no($wx_no) {
    $MerWxSetting = M('MerWxSetting');

    $data = $MerWxSetting->where(array(
        'wx_no' => $wx_no
      ))
      ->find();

    return $data ? $data : array();
  }

  function _login($data) {
    $cookie_file = tempnam('Public/tmp', 'wechat_cookie');
    $login_url = 'https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN';

    // 模拟登录
    $login_ret = $this->_http_post($login_url, $data, $cookie_file);
    if (!$login_ret ['status']) {
      return $login_ret;
    }

    // 取公众号信息
    $info_url = "https://mp.weixin.qq.com/cgi-bin/settingpage?t=setting/index&action=index&token=" . $login_ret ['token'] . "&lang=zh_CN";
    $content = $this->_http_get($info_url, $cookie_file);

    // 解析信息
    $ret ['data'] = $this->_parse_html($content, $cookie_file);
    return ajax_arr('OK', TRUE, $ret);
  }

  function _http_post($url, $data, $cookie_file = '') {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_REFERER, 'https://mp.weixin.qq.com');
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER ['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    // 优化
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Expect: '
    ));
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);

    $result = curl_exec($ch);
    curl_close($ch);
    if (!$result || empty($result)) {
      return ajax_arr('登录失败，请稍后再试');
    }

    $ret_data = json_decode($result, TRUE);

    if ($ret_data ['base_resp'] ['ret'] != 0) {
      return ajax_arr($ret_data ['base_resp'] ['err_msg']);
    }
    // 取token /cgi-bin/home?t=home/index&lang=zh_CN&token=1953680001
    $pos = strrpos($ret_data ['redirect_url'], '=');
    $token = substr($ret_data ['redirect_url'], $pos + 1);

    return ajax_arr('登录成功', TRUE, array(
      'token' => $token
      ));
  }

  function _http_get($url, $cookie_file = '') {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // curl_setopt($ch,CURLOPT_REFERER,'https://mp.weixin.qq.com');
    // curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT'] );
    $content = curl_exec($ch);
    curl_close($ch);

    return $content;
  }

  function _parse_html($content, $cookie_file) {
    // 内容
    $meta_content = array();
    preg_match_all('/<div class="meta_content">(.*?)<\/div>/is', $content, $meta_content);
    $meta_key = array();
    preg_match_all('/<h4>(.*?)<\/h4>/is', $content, $meta_key);

    $ret = array();
    // 图标
    $img_array = array();
    preg_match_all('/<img class="meta_pic".*?src="(.*?)".*?>/is', $meta_content [1] [0], $img_array);
    // $ret['icon'] = 'https://mp.weixin.qq.com' . $img_array[1][0] ;
    $ret ['icon'] = $this->_save_icon_img($img_array [1] [0], $cookie_file);

    // 二维码
    $qrocde_array = array();
    preg_match_all('/<img .*?src="(.*?)" class="qrcode_pic" .*?>/is', $meta_content [1] [1], $qrocde_array);
    $ret ['qrcode'] = $this->_save_icon_img($qrocde_array [1] [0], $cookie_file);

    // 微信名称
    $ret ['name'] = trim($meta_content [1] [2]);

    // 微信号
    $wx_no = array();
    preg_match_all('/<span>(.*?)<\/span>/is', $meta_content [1] [3], $wx_no);
    $ret ['wx_no'] = $wx_no [1] [0];

    $ret ['type'] = $this->type_text [trim(substr(trim($meta_content [1] [4]), 0, 10))]; // 类型
    $ret ['desc'] = trim($meta_content [1] [5]); // 介绍
    $ret ['auth_status'] = strpos($meta_content [1] [6], '微信认证') ? 1 : 0; // 微信认证

    if ($meta_key [1] [7] == '客服电话') {
      $ret ['phone'] = trim($meta_content [1] [7]); // 客服电话
      $ret ['address'] = trim($meta_content [1] [8]); // 地址
      $ret ['org'] = trim($meta_content [1] [9]); // 组织
      $ret ['ys_id'] = trim($meta_content [1] [11]); // 原始ID
    } else {
      $ret ['address'] = trim($meta_content [1] [7]); // 地址
      $ret ['org'] = trim($meta_content [1] [8]); // 组织
      $ret ['ys_id'] = trim($meta_content [1] [10]); // 原始ID
    }

    return $ret;
  }

  function update($id, $data) {
    $MerWxSetting = M('MerWxSetting');

    $ret = $MerWxSetting->where("id = %d", $id)
      ->save($data);
    if ($ret) {
      return ajax_arr('编辑成功', TRUE);
    } else {
      return ajax_arr('编辑失败', FALSE);
    }
  }
      
  function delete($ids) {
    $MerWxSetting = M('MerWxSetting');
    $old_data = $this->get_by_id($ids);
    if (empty($old_data)) {
      return ajax_arr('数据未找到', FALSE);
    }

    delete_file($old_data ['icon']);
    delete_file($old_data ['qrcode']);

    $ret = $MerWxSetting->delete($ids);
    if ($ret == 0) {
      return ajax_arr('未删除任何数据', FALSE);
    } else if (!$ret) {
      return ajax_arr('删除失败', FALSE);
    } else {
      return ajax_arr('删除' . $ret . '行数据', TRUE);
    }
  }

  function _save_icon_img($url, $cookie_file) {
    $img_url = 'https://mp.weixin.qq.com' . $url;

    $icon_content = $this->_http_get($img_url, $cookie_file);
    $file_name = rand_string(16);

    $file_path = 'Public/upload/icon/' . date('Ym');
    if (!file_exists($file_path)) {
      mkdir($file_path, 0777);
    }

    $file_name_full = $file_path . '/' . $file_name;
    file_put_contents($file_name_full, $icon_content);
    return $file_name_full;
  }

  function get_by_appid_appsecret($app_id, $app_secret) {
    $MerWxSetting = M('MerWxSetting');

    $data = $MerWxSetting->where('app_id = "%s" and app_secret ="%s"', $app_id, $app_secret)
      ->find();

    return $data ? $data : array();
  }

  function save_access_token_by_appid_appsecret($app_id, $app_secret, $save_data) {
    $MerWxSetting = M('MerWxSetting');

    $ret = $MerWxSetting->where('app_id = "%s" and app_secret ="%s"', $app_id, $app_secret)
      ->save($save_data);

    if ($ret) {
      return ajax_arr('保存成功', TRUE);
    } else {
      return ajax_arr('保存失败', FALSE);
    }
  }

  /**
   * 设置最后一次操作时间，方便聊天
   *
   * @param unknown $openid          
   * @param string $provider          
   */
  function set_last_op($openid, $provider = "wechat") {
    $MerUserOpenid = M('MerUserOpenid');
    $MerUserOpenid->where(array(
        "provider" => $provider,
        "openid" => $openid
      ))
      ->setField("last_op_time", date("Y-m-d h:i:s"));
  }

  function get_by_id_merid( $wx_id , $mer_id ) {
    $MerWxSetting = M('MerWxSetting');
    $data = $MerWxSetting->where('mer_id = %d and id = %d' , $mer_id , $wx_id )->find();
    //echo $MerWxSetting->_sql();
    return $data ? $data : array();
  }
  
}
